﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Threading.Tasks;

namespace Coldairarrow.Api
{
    public class OuterImgMiddleware
    {
        public static string RootPath { get; set; } //配置文件读取绝对位置
        private readonly RequestDelegate _next;
        public OuterImgMiddleware(RequestDelegate next, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var path = context.Request.Path.ToString();
            var headersDictionary = context.Request.Headers;
            if (context.Request.Method == "GET" && !string.IsNullOrEmpty(path))
            {
                if (path.Contains("/upload"))
                {
                    string physicPath = GetAbsolutePath(context, $"~{path}");
                    FileInfo file = new FileInfo(physicPath);
                    if (file.Exists)
                    {
                        int length = path.LastIndexOf(".") - path.LastIndexOf("/") - 1;
                        context.Response.Headers["Etag"] = path.Substring(path.LastIndexOf("/") + 1, length);
                        context.Response.Headers["Last-Modified"] = new DateTime(2018).ToString("r");
                        context.Response.Headers["Accept-Ranges"] = "bytes";
                        //context.Response.Headers["Content-Length"] = file.Length.ToString();
                        if (path.EndsWith(".mp4"))
                        {
                            context.Response.ContentType = "video/mp4";
                            //分段读取内容
                            DownloadRange download = new DownloadRange(context);
                            download.WriteFile(physicPath);
                        }
                        else
                        {
                            context.Response.ContentType = "image/jpeg";
                            context.Response.Headers["Cache-Control"] = "public"; //指定客户端，服务器都处理缓存
                            await context.Response.SendFileAsync(physicPath);
                        }
                    }
                    return;
                }
            }

            await _next(context);
        }

        protected string GetAbsolutePath(HttpContext context, string virtualPath)
        {
            string path = virtualPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
            if (path[0] == '~')
                path = path.Remove(0, 2);
            string rootPath = context.RequestServices.GetService<IWebHostEnvironment>().WebRootPath;

            return Path.Combine(rootPath, path);
        }
    }
    public static class MvcExtensions
    {
        public static IApplicationBuilder UseOutImg(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<OuterImgMiddleware>();
        }
    }
}
